package com.alipay.rebate.shop.utils;

import com.alibaba.fastjson.JSON;
import com.alipay.rebate.shop.constants.ProductConstant;
import com.alipay.rebate.shop.exceptoin.PrivilegeLinkFailedException;
import com.alipay.rebate.shop.helper.AppSettingsHelper;
import com.alipay.rebate.shop.helper.InterfaceStatisticsHelper;
import com.alipay.rebate.shop.model.Product;
import com.alipay.rebate.shop.pojo.dataoke.*;
import com.alipay.rebate.shop.scheduler.DataokeCidMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

public class DataokeUtil {

    @Autowired
    InterfaceStatisticsHelper interfaceStatisticsHelper;

    private static final String appSecret = "2db0715c7a6e202b1739cea31150c344";//应用sercret
    private static final String appKey = "5ce634df8a3a8"; //应用key
    private static Gson gson = new GsonBuilder().create();
    private static ObjectMapper objectMapper = new ObjectMapper();
    private static Logger logger = LoggerFactory.getLogger(DataokeUtil.class);

    public static Object getFriendsCircleListReq(FriendsCircleListReq req) throws IOException {
        String url = "https://openapi.dataoke.com/api/goods/friends-circle-list";
        TreeMap<String, String> paraMap = new TreeMap<>();
        paraMap.put("version", "v1.2.2");
        paraMap.put("appKey", AppSettingsHelper.getDataokeAppKey());
        paraMap.put("pageId", req.getPageId());

        if (req.getSubcid() != null) {
            paraMap.put("subcid", req.getSubcid());
        }
        if (req.getCids() != null) {
            paraMap.put("cids", req.getCids());
        }
        if (req.getSort() != null) {
            paraMap.put("sort", req.getSort());
        }
        if (req.getPageSize() != null){
            paraMap.put("pageSize", String.valueOf(req.getPageSize()));
        }
        if (req.getFreeshipRemoteDistrict() != null) {
            paraMap.put("freeshipRemoteDistrict", String.valueOf(req.getFreeshipRemoteDistrict()));
        }
        if (req.getGoodsId() != null){
            paraMap.put("goodsId", String.valueOf(req.getGoodsId()));
        }
        if (req.getPre() != null){
            paraMap.put("pre", String.valueOf(req.getPre()));
        }
        paraMap.put("sign", SignMD5Util.getSignStr(paraMap, AppSettingsHelper.getDataokeAppSecret()));
        String sendGetObject = HttpUtils.sendGet(url, paraMap);
//        DataokeProductListRsp rsp = gson.fromJson(sendGetObject, DataokeProductListRsp.class);
        Object readValue = objectMapper.readValue(sendGetObject, Object.class);
        return readValue;
    }

    public static DataokeProductListRsp getFriendsCircleListReqTwo(String pageId) throws IOException {
        String url = "https://openapi.dataoke.com/api/goods/friends-circle-list";
        TreeMap<String, String> paraMap = new TreeMap<>();
        paraMap.put("version", "v1.2.2");
        paraMap.put("pageId",pageId);
        paraMap.put("appKey", AppSettingsHelper.getDataokeAppKey());
        paraMap.put("sign", SignMD5Util.getSignStr(paraMap, AppSettingsHelper.getDataokeAppSecret()));
        String sendGetObject = HttpUtils.sendGet(url, paraMap);
        DataokeProductListRsp rsp = gson.fromJson(sendGetObject, DataokeProductListRsp.class);
        return rsp;
    }



    private static TreeMap<String, String> getCommonTreeMap(String pageId) {
        TreeMap<String, String> paraMap = new TreeMap<>();
        paraMap.put("version", "v1.2.1");
        paraMap.put("appKey", AppSettingsHelper.getDataokeAppKey());
        paraMap.put("pageId", pageId);
        return paraMap;
    }

    private static DataokeProductListRsp send(String url, TreeMap<String, String> paraMap) {
        paraMap.put("sign", SignMD5Util.getSignStr(paraMap, AppSettingsHelper.getDataokeAppSecret()));
        String body = HttpUtils.sendGet(url, paraMap);
        DataokeProductListRsp rsp = gson.fromJson(body, DataokeProductListRsp.class);
        return rsp;
    }

    public static DataokePrivilegeLinkRsp getPrivilegeLink(String goodsId) {
        String url = "https://openapi.dataoke.com/api/tb-service/get-privilege-link";
        TreeMap<String, String> paraMap = new TreeMap<>();
        paraMap.put("version", "v1.0.0");
        paraMap.put("appKey", AppSettingsHelper.getDataokeAppKey());
        paraMap.put("goodsId", goodsId);
        paraMap.put("sign", SignMD5Util.getSignStr(paraMap, AppSettingsHelper.getDataokeAppSecret()));
        String body = HttpUtils.sendGet(url, paraMap);
        DataokePrivilegeLinkRsp dataokeResponse = gson.fromJson(body, DataokePrivilegeLinkRsp.class);
        if (dataokeResponse == null || dataokeResponse.getData() == null) {
            throw new PrivilegeLinkFailedException();
        }
        return dataokeResponse;
    }

    public static DataokeProductListRsp getAllProducts(String pageId) {
        String url = "https://openapi.dataoke.com/api/goods/get-goods-list";
        TreeMap<String, String> paraMap = getCommonTreeMap(pageId);
        paraMap.put("pageSize", "200");
        return send(url, paraMap);
    }

    public static DataokeProductListRsp dataokeGoodsFriendsCircleList(String pageId){
        String url = "https://openapi.dataoke.com/api/goods/get-goods-list";
        TreeMap<String, String> paraMap = new TreeMap<>();
        paraMap.put("pageId",pageId);
        paraMap.put("version", "v1.2.2");
        paraMap.put("appKey", AppSettingsHelper.getDataokeAppKey());
        paraMap.put("sign", SignMD5Util.getSignStr(paraMap, AppSettingsHelper.getDataokeAppSecret()));
        String sendGetObject = HttpUtils.sendGet(url, paraMap);
        DataokeProductListRsp rsp = gson.fromJson(sendGetObject, DataokeProductListRsp.class);
        return rsp;
    }

    public static DataokeProductListRsp getAllProducts(DataokeProductSearchReq req) {

        try {
            String url = "https://openapi.dataoke.com/api/goods/get-goods-list";
            TreeMap<String, String> paraMap = null;
            paraMap = sendAndGetObj(url, req);
            paraMap.put("version", "v1.2.1");
            paraMap.put("appKey", AppSettingsHelper.getDataokeAppKey());
            paraMap.put("pageId", req.getPageId());
            return send(url, paraMap);
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("exception is : {}", e.getMessage());
            throw new RuntimeException();
        }

    }

    public static DataokeProductListRsp pullProductsByTime(
            String pageId,
            String startTime,
            String endTime
    ) {


        String url = "https://openapi.dataoke.com/api/goods/pull-goods-by-time";
        TreeMap<String, String> paraMap = getCommonTreeMap(pageId);
        paraMap.put("startTime", startTime);
        paraMap.put("endTime", endTime);
        paraMap.put("pageSize", "200");
        return send(url, paraMap);
    }

    public static DataokeProductListRsp getNewestProducts(String pageId) {


        String url = "https://openapi.dataoke.com/api/goods/get-newest-goods";
        TreeMap<String, String> paraMap = getCommonTreeMap(pageId);
        paraMap.put("pageSize", "200");
        return send(url, paraMap);
    }

    public static DataokeProductListRsp getStaleProductsByTime(
            String pageId,
            String startTime,
            String endTime
    ) {
        String url = "https://openapi.dataoke.com/api/goods/get-stale-goods-by-time";
        TreeMap<String, String> paraMap = getCommonTreeMap(pageId);
        paraMap.put("startTime", startTime);
        paraMap.put("endTime", endTime);
        paraMap.put("pageSize", "200");
        return send(url, paraMap);
    }

    public static Object getDtkSearchGoods(DataokeProductSearchReq dtkProductSearchReq) {

        try {
            String url = "https://openapi.dataoke.com/api/goods/get-dtk-search-goods";
            TreeMap<String, String> paraMap = null;
            paraMap = sendAndGetObj(url, dtkProductSearchReq);
            logger.debug("paraMap is: {}", paraMap);
            paraMap.put("sign", SignMD5Util.getSignStr(paraMap, AppSettingsHelper.getDataokeAppSecret()));
            String responseBody = HttpUtils.sendGet(url, paraMap);
            return objectMapper.readValue(responseBody, Object.class);
        } catch (Exception e) {
            logger.debug("exception is : {}", e.getMessage());
            throw new RuntimeException();
        }

    }

    public static Object searchSuggestion(
            String keyWords,
            Integer type,
            String version
    ) {

        try {
            String url = "https://openapi.dataoke.com/api/goods/search-suggestion";
            TreeMap<String, String> paraMap = new TreeMap<>();
            paraMap.put("version", "v1.0.2");
            paraMap.put("appKey", AppSettingsHelper.getDataokeAppKey());
            if (!StringUtils.isEmpty(keyWords)) {
                paraMap.put("keyWords", keyWords);
            }
            if (type != null) {
                paraMap.put("type", String.valueOf(type));
            }
            if (!StringUtils.isEmpty(version)) {
                paraMap.put("version", version);
            }
            paraMap.put("sign", SignMD5Util.getSignStr(paraMap, AppSettingsHelper.getDataokeAppSecret()));
            String responseBody = HttpUtils.sendGet(url, paraMap);
            Object obj = null;
            obj = objectMapper.readValue(responseBody, Object.class);
            return obj;
        } catch (IOException e) {
            logger.debug("exception is : {}", e.getMessage());
            throw new RuntimeException();
        }

    }

    public static Object getGoodsList(DataokeGoodsList dataokeGoodsList) {

        try {
            String url = "https://openapi.dataoke.com/api/goods/get-goods-list";
            TreeMap<String, String> paraMap = null;
            paraMap = sendAndGetObj(url, dataokeGoodsList);
            paraMap.put("sign", SignMD5Util.getSignStr(paraMap, AppSettingsHelper.getDataokeAppSecret()));
            String body = HttpUtils.sendGet(url, paraMap);
            return objectMapper.readValue(body, Object.class);
        } catch (Exception e) {

            logger.debug("exception is : {}", e.getMessage());
            throw new RuntimeException();
        }
    }

    public static SuperCategoryResponse getSuperCategory() {

        try {
            String url = "https://openapi.dataoke.com/api/category/get-super-category";
            TreeMap<String, String> paraMap = new TreeMap<>();

            paraMap.put("version", "v1.1.0");
            paraMap.put("appKey", AppSettingsHelper.getDataokeAppKey());
            paraMap.put("sign", SignMD5Util.getSignStr(paraMap, AppSettingsHelper.getDataokeAppSecret()));
            logger.debug("paraMap is : {}", paraMap);
            String responseBody = HttpUtils.sendGet(url, paraMap);
            return objectMapper.readValue(responseBody, SuperCategoryResponse.class);
        } catch (IOException e) {
            logger.debug("exception is : {}", e.getMessage());
            throw new RuntimeException();
        }
    }

    public static Object getRankingList(DataokeRankingListReq dataokeRankingListReq) {

        try {
            String url = "https://openapi.dataoke.com/api/goods/get-ranking-list";
            TreeMap<String, String> paraMap = null;
            paraMap = sendAndGetObj(url, dataokeRankingListReq);
            paraMap.put("sign", SignMD5Util.getSignStr(paraMap, AppSettingsHelper.getDataokeAppSecret()));
            logger.debug("paraMap is : {}", paraMap);
            String responseBody = HttpUtils.sendGet(url, paraMap);
            return objectMapper.readValue(responseBody, Object.class);
        } catch (Exception e) {
            logger.debug("exception is : {}", e.getMessage());
            throw new RuntimeException();
        }
    }

    private static TreeMap<String, String> sendAndGetObj(String url, Object request) throws Exception {
        TreeMap<String, String> paraMap = new TreeMap<>();
        paraMap.put("version", "v2.1.1");
        paraMap.put("appKey", AppSettingsHelper.getDataokeAppKey());
        ReflectUtil.buildParaMap(paraMap, request);
        logger.debug("paraMap is: {}", paraMap);
        return paraMap;
    }

    public static Product convert2Product(DataokeProduct dataokeProduct) {
        Product product = new Product();
        product.setGoodsId(Long.valueOf(dataokeProduct.getGoodsId()));
        product.setItemLink(dataokeProduct.getItemLink());
        product.setTitle(dataokeProduct.getTitle());
        product.setDtitle(dataokeProduct.getDtitle());
        product.setDescription(dataokeProduct.getDesc());
        if (dataokeProduct.getCid() != null) {
            product.setCid(DataokeCidMapper.getCid(dataokeProduct.getCid()));
        }
        product.setTbcid(dataokeProduct.getTbcid());
        product.setMainPic(dataokeProduct.getMainPic());
        product.setMarketingMainPic(dataokeProduct.getMarketingMainPic());
        product.setOriginalPrice(dataokeProduct.getOriginalPrice());
        product.setActualPrice(dataokeProduct.getActualPrice());
        product.setDiscounts(dataokeProduct.getActualPrice());
        product.setCommissionType(dataokeProduct.getCommissionType());
        product.setCommissionRate(dataokeProduct.getCommissionRate());
        product.setCouponLink(dataokeProduct.getCouponLink());
        product.setCouponTotalNum(dataokeProduct.getCouponTotalNum());
        product.setCouponReceiveNum(dataokeProduct.getCouponReceiveNum());
        product.setCouponEndTime(dataokeProduct.getCouponEndTime());
        product.setCouponStartTime(dataokeProduct.getCouponStartTime());
        product.setCouponPrice(dataokeProduct.getCouponPrice());
        product.setCouponConditions(dataokeProduct.getCouponConditions());
        product.setMonthSales(dataokeProduct.getMonthSales());
        product.setTwoHoursSales(dataokeProduct.getTwoHoursSales());
        product.setDailySales(dataokeProduct.getDailySales());
        product.setBrand(dataokeProduct.getBrand());
        product.setBrandId(dataokeProduct.getBrandId());
        product.setBrandName(dataokeProduct.getBrandName());
        product.setCreateTime(dataokeProduct.getCreateTime());
        product.setTchaoshi(dataokeProduct.getTchaoshi());
        product.setActivityType(dataokeProduct.getActivityType());
        product.setActivityStartTime(dataokeProduct.getActivityStartTime());
        product.setActivityEndTime(dataokeProduct.getActivityEndTime());
        product.setShopType(dataokeProduct.getShopType());
        product.setHaitao(dataokeProduct.getHaitao());
        product.setGoldSellers(dataokeProduct.getGoldSellers());
        product.setSellerId(dataokeProduct.getSellerId());
        product.setShopName(dataokeProduct.getShopName());
        product.setShopLevel(dataokeProduct.getShopLevel());
        product.setDescScore(dataokeProduct.getDescScore());
        product.setDsrScore(dataokeProduct.getDsrScore());
        product.setDsrPercent(dataokeProduct.getDsrPercent());
        product.setShipScore(dataokeProduct.getShipScore());
        product.setShipPercent(dataokeProduct.getShipPercent());
        product.setServiceScore(dataokeProduct.getServiceScore());
        product.setServicePercent(dataokeProduct.getServicePercent());
        product.setHotPush(dataokeProduct.getHotPush());
        product.setTeamName(dataokeProduct.getTeamName());
        product.setProductType(ProductConstant.DATAOKE_TYPE);
        product.setHzQuanOver(dataokeProduct.getHzQuanOver());
        product.setQuanMLink(dataokeProduct.getQuanMLink());
        if (dataokeProduct.getFreeshipRemoteDistrict() != null){
            product.setProductType(3);
        }
        product.setFreeshipRemoteDistrict(dataokeProduct.getFreeshipRemoteDistrict());
        product.setCircleText(dataokeProduct.getCircleText());

        return product;
    }


}
